import { contextBridge, IpcRenderer, ipcRenderer, shell } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

import { useLoading } from './loading'

const { removeLoading } = useLoading()
// Custom APIs for renderer
const api = {}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
    contextBridge.exposeInMainWorld('shell', shell)
    contextBridge.exposeInMainWorld('removeLoading', removeLoading)
    contextBridge.exposeInMainWorld('ipcRenderer', {
      ...ipcRenderer,
      // `exposeInMainWorld` will not expose attribute and mothods from the prototype
      on(...args: Parameters<IpcRenderer['on']>) {
        return ipcRenderer.on(...args)
      }
    })
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
  window.shell = shell
}
